package com.init.iblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.init.iblog.constants.SystemConstants;
import com.init.iblog.domain.ResponseResult;
import com.init.iblog.domain.entity.Comment;
import com.init.iblog.domain.entity.User;
import com.init.iblog.domain.vo.CommentVo;
import com.init.iblog.domain.vo.PageVo;
import com.init.iblog.enums.AppHttpCodeEnum;
import com.init.iblog.exception.SystemException;
import com.init.iblog.mapper.CommentMapper;
import com.init.iblog.service.CommentService;
import com.init.iblog.service.UserService;
import com.init.iblog.utils.BeanCopyUtils;
import com.init.iblog.utils.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * (Comment)表服务实现类
 *
 * @author makejava
 * @since 2023-02-23 19:38:19
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private UserService userService;

    /**
     * 获取评论列表
     * @param blogId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseResult commentList(String commentType,Long blogId, Integer pageNum, Integer pageSize) {
        //查询对应文章的根评论
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();

        /**
         * 对blogId进行判断
         * 当blogId为空时，表示为友链评论，则当为文章评论时，去查询对应的文章id
         * queryWrapper.eq(条件，执行)
         */
        queryWrapper.eq(SystemConstants.ARTICLE_COMMENT.equals(commentType),Comment::getBlogId,blogId);
        //根评论 rootId为-1
        queryWrapper.eq(Comment::getRootId, SystemConstants.ROOT_COMMENT);


        //评论类型
        queryWrapper.eq(Comment::getType,commentType);
        //分页查询
        Page<Comment> page = new Page(pageNum,pageSize);
        page(page,queryWrapper);

        List<CommentVo> commentVoList = toCommentVoList(page.getRecords());

        //查询所有根评论对应的子评论集合，并且赋值给对应的属性
        for (CommentVo commentVo:commentVoList) {
            //查询对应的子评论
            System.out.println("=======》》》》》》》查看评论详情" + commentVo.toString());
            Long createBy = commentVo.getCreateBy();
            User user = userService.getById(createBy);
            commentVo.setAvatar(user.getAvatar());
            List<CommentVo> children = getChildren(commentVo.getId());
            //进行赋值
            commentVo.setChildren(children);
        }

        return ResponseResult.okResult(new PageVo(commentVoList,page.getTotal()));
    }

    @Override
    public ResponseResult addComment(Comment comment) {

        /**
         * 定义了处理器handler下的mybatisPlus包下的MyMetaObjectHandler，以下操作会自动填充
         */

        //从token中获取用户id
        //comment.setCreateBy(SecurityUtils.getUserId());
        //时间赋值

        //评论内容不能为空
        if(!StringUtils.hasText(comment.getContent())){
            throw new SystemException(AppHttpCodeEnum.CONTENT_NOT_NULL);
        }
        save(comment);
        return ResponseResult.okResult();
    }


    /**
     * Comment集合转化为CommentVo集合
     * CommentVo中还需要有评论者昵称且若该评论不为根品论时，还需要查询被评论者昵称
     * @param list
     * @return
     */
    private List<CommentVo> toCommentVoList(List<Comment> list){
        List<CommentVo> commentVoList = BeanCopyUtils.copyBeanList(list, CommentVo.class);
        //遍历vo集合
        for (CommentVo commentVo : commentVoList) {

            //通过createBy查询用户名的昵称并赋值（查询评论创建人昵称）
            System.out.println("评论创建者id"+commentVo.getCreateBy());
            String nickname = userService.getById(commentVo.getCreateBy()).getNickname();
            commentVo.setUsername(nickname);
            //通过toCommentUserId查询用户的昵称并赋值（查询被回复者昵称,当评论者为根评论，则没有被回复者）
            //如果toCommentUserId不为-1才进行查询
            if(commentVo.getToCommentUserId() != -1){  //该评论是回复别人的评论的
                String toCommentUserName = userService.getById(commentVo.getToCommentUserId()).getNickname();
                commentVo.setToCommentUserName(toCommentUserName);
            }
        }
        return commentVoList;
    }

    /**
     * 根据根评论的id查询所对应子评论的集合
     * @param id
     * @return
     */
    private List<CommentVo> getChildren(Long id){

        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getRootId,id);
        //根据时间排序
        queryWrapper.orderByAsc(Comment::getCreateTime);
        List<Comment> comments = list(queryWrapper);

        List<CommentVo> commentVoList = toCommentVoList(comments);
        return commentVoList;
    }
}
